#include "app_pool.h"

static char *pool_name = "/app_pool_mq";
static mqd_t mqd_handler;
static pthread_t *thread_handler;
static int thread_num;
void *app_pool_thread(void *arg)
{
    Task task;
    while (1)
    {
        mq_receive(mqd_handler, (char *)&task, sizeof(Task), NULL);
        task.func(task.arg);
    }
}
// 初始化
int app_pool_init(int max_thread_num)
{
    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = sizeof(Task);

    mqd_handler = mq_open(pool_name, O_RDWR | O_CREAT, 0666, &attr);
    if (mqd_handler == -1)
    {
        log_info("mq_open error");
        return -1;
    }

    thread_handler = (pthread_t *)malloc(sizeof(pthread_t) * max_thread_num);
    if (thread_handler == NULL)
    {
        log_info("malloc error");
        return -1;
    }
    thread_num = max_thread_num;
    for (int i = 0; i < max_thread_num; i++)
    {
        pthread_create(&thread_handler[i], NULL, app_pool_thread, NULL);
    }

    return 0;
}
// 关闭
void app_pool_close()
{
    mq_unlink(pool_name);
    for (int i = 0; i < thread_num; i++)
    {
        pthread_cancel(thread_handler[i]);
    }
}
// 添加任务
int app_pool_add_task(void (*func)(void *), void *args)
{
    Task task = {
        task.func = func,
        task.arg = args,
    };

    return mq_send(mqd_handler, (char *)&task, sizeof(Task), 1);
}